package com.bookstore.servlet;

import com.bookstore.entity.Product;
import com.bookstore.service.ProductService;
import com.bookstore.service.impl.ProductServiceImpl;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

@WebServlet("/uploadProduct.do")
public class UpdateProductServlet extends HttpServlet {
    ProductService productService = new ProductServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.判断上传的数据是否为多段表单数据（multipart-formdata）
        if (ServletFileUpload.isMultipartContent(req)) {
            //创建FileItemFactory 工厂实现类
            FileItemFactory fileItemFactory = new DiskFileItemFactory();
            //创建用于解析上传数据的工具类 ServletFileUpload
            ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
            Product product = new Product();
            try {
                //解析上传的数据 得到每个表单项FileItem
                List<FileItem> list = servletFileUpload.parseRequest(req);
                //循环判断：每一个表单项是普通文本类型，还是文件类型
                for (int i = 0; i < list.size(); i++) {
                    FileItem fileItem = list.get(i);
                    if (fileItem.isFormField()) {
                        if ("name".equals(fileItem.getFieldName())) {
                            product.setName(fileItem.getString("UTF-8"));
                        } else if ("price".equals(fileItem.getFieldName())) {
                            product.setPrice(Double.valueOf(fileItem.getString("UTF-8")));
                        } else if ("category".equals(fileItem.getFieldName())) {
                            product.setCategory(fileItem.getString("UTF-8"));
                        } else if ("pNum".equals(fileItem.getFieldName())) {
                            product.setpNum(Integer.valueOf(fileItem.getString("UTF-8")));
                        } else if ("description".equals(fileItem.getFieldName())) {
                            product.setDescription(fileItem.getString("UTF-8"));
                        }
                    } else {
                        //按照当前毫秒值+文件后缀名的方式生成文件名
                        long timeMills = System.currentTimeMillis();
                        String originalFileName = fileItem.getName();
                        //1.2.jpg ==> "1"  "2"  "jpg"
                        String[] split = originalFileName.split("\\.");
                        String s = split[split.length - 1];
                        //获取当前上传文件的后缀名
                        String newFileName = new StringBuilder(s).insert(0, ".").insert(0, timeMills).toString();
                        //生成一个按照规则的文件名
                        product.setImgUrl(newFileName);
                        fileItem.write(new File("D:\\imgUpload\\" + newFileName));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            int result = productService.insertProduct(product);
            //直接跳转回商品查询界面
            resp.sendRedirect("./product.do?action=queryAll");
        }
    }
}
